package com.wxb.plugin.core.gen;

import com.google.common.collect.Lists;
import com.wxb.plugin.action.Config;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import static com.wxb.plugin.core.gen.GenWord.getTimeStamp;
import static com.wxb.plugin.core.gen.InterfaceApiGen2.subHeader;

/**
 * @author wxb
 * @createTime 2025/3/18 16:56
 */
public class GenMarkDown {

    public static String toFile(List<ControllerApiInfo> controllerApiInfos, Config config) {

        String filePath = config.getPath() + config.getFilePre() + getTimeStamp() + ".md";
        // 'true' 表示以追加模式打开文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
            // 写入头
            addHead(writer);
            // 写入内容
            for (int i = 1; i <= controllerApiInfos.size(); i++) {
                ControllerApiInfo info = controllerApiInfos.get(i-1);
                if (info.hide) {
                    continue;
                }
                // 设置一级标题
                addParagraph(writer, i + ". " + info.note, 0);
                int titleCount = 1;
                for (MethodApiInfo method : info.methodApiInfos) {
                    if (method.hide) {
                        continue;
                    }
                    fillMethodApi(writer, method, i + "." + titleCount + ". ");
                    titleCount++;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            // 处理异常
        }
        return config.getPath();
    }

    public static void fillMethodApi(BufferedWriter document, MethodApiInfo api, String serial) throws IOException {
        if (api == null) {
            return;
        }
        // 设置一级标题
        addParagraph(document, serial + api.title, 1);

        // 业务描述
        addParagraph(document, subHeader[0] + ": " + api.businessDesc, 2);

        // 接口提供方
        addParagraph(document, subHeader[1] + ": " + api.interfaceProvide, 2);

        // 接口地址
        addParagraph(document, subHeader[2] + ": ", 2);
        for (String u : api.url) {
            addParagraph(document, u, 3);
        }

        // 接口请求字段
        addEntityFields(document, api.paramEntities, subHeader[3], 2);
        // 接口响应字段
        addEntityFields(document, api.returnEntities, subHeader[4], 2);

        // 请求示例报文
        addParagraph(document, subHeader[5] + ": ", 2);
        addParagraph(document, api.requestExample, 4);

        // 响应示例报文
        addParagraph(document, subHeader[6] + ": ", 2);
        addParagraph(document, api.responseExample, 4);
    }

    public static void addParagraph(BufferedWriter writer, String text, int level) throws IOException {
        String prefix = "";
        String suffix = "";

        switch (level) {
            case 0:
                prefix = "### ";
                break;
            case 1:
                prefix = "####       ";
                break;
            case 2:
                prefix = "- ##### ";
                break;
            case 3:
                prefix = "        ";
                break;
            case 4:
                prefix = "  ```json\n";
                suffix = "\n  ```";
                break;
            default:
        }
        writeLine(writer, prefix + text + suffix);
        // 写入一个新行符，以便下次写入时换行
        writer.newLine();
        writer.newLine();
    }

    public static void addHead(BufferedWriter writer) throws IOException {
        // 标题
        writeLine(writer, "## \t\t\t\t\tAPI DOC");
        writer.newLine();
        // 作者
        writeLine(writer, "Author: swagger hepler");
        writer.newLine();
        writer.newLine();
        writer.newLine();
    }

    public static void writeLine(BufferedWriter writer, String text) throws IOException {
        // 写入内容
        writer.write(text);
        // 写入一个新行符，以便下次写入时换行
        writer.newLine();
    }

    public static void addEntityFields(BufferedWriter document, List<MethodApiInfo.FieldInfo> api, String text, int level) throws IOException {
        // 接口请求字段
        addParagraph(document, text + ": ", level);
        if (api != null && !api.isEmpty()) {
            for (MethodApiInfo.FieldInfo entityInfo : api) {
                String info = StringUtil.isNotBlank(entityInfo.nameCn) ? "(" + entityInfo.nameCn + ")" : "";
                addParagraph(document, (entityInfo.requestType == null ? "" : entityInfo.requestType)
                        + "  "
                        + entityInfo.nameEn
                        + info
                        + ": ", 3);
                if (entityInfo instanceof MethodApiInfo.EntityInfo entity) {
                    addTable(document, entity.fieldInfos);
                } else {
                    addTable(document, Lists.newArrayList(entityInfo));
                }
            }
        }
    }

    public static void addTable(BufferedWriter writer, List<MethodApiInfo.FieldInfo> fieldInfos) throws IOException {
        if(fieldInfos == null || fieldInfos.isEmpty()) {
            return;
        }
        // 写入内容
        writeLine(writer, "  | **序号** | **中文域名** | **英文域名** | **类型** | **必填** | **说明** |");
        writeLine(writer, "  | :------: | :----------: | :----------: | :------: | :------: | :------: |");
        StringBuilder sb = new StringBuilder();
        for (MethodApiInfo.FieldInfo fieldInfo : fieldInfos) {
            sb.append("  | ");
            sb.append(fieldInfo.serial).append(" | ");
            sb.append(fieldInfo.nameCn).append(" | ");
            sb.append(fieldInfo.nameEn).append(" | ");
            sb.append(fieldInfo.type).append(" | ");
            sb.append(fieldInfo.isNecessary).append(" | ");
            sb.append(fieldInfo.information).append(" | ");
            writeLine(writer, sb.toString());
            // 清空
            sb.setLength(0);
        }
        // 写入一个新行符，以便下次写入时换行
        writer.newLine();
        writer.newLine();
    }
}
